package main

import (
	"log"
	"math/rand"
	"sync"
	"time"
)

func getUser(n int) chan int {
	ch := make(chan int)
	for i := 0; i < n; i++ {
		go func(ch chan int) {
			if rand.Intn(3) == 2 {
				log.Printf("玩家退出....")
				getUser(1)
			}
			time.Sleep(time.Duration(rand.Intn(1000)) * time.Microsecond)
			ch <- rand.Intn(1000)
		}(ch)
	}
	return ch
}

func partition1() {
	ch := getUser(10)
	s := make([]int, 0, 10)
	t := time.NewTicker(time.Second)
	defer t.Stop()
	for {
		if len(s) > 9 {
			break
		}
		select {
		case a := <-ch:
			log.Print(a)
			s = append(s, a)
		case <-t.C:
			log.Print("len:", len(s))
		default:
			time.Sleep(time.Millisecond)
			log.Print("default")
		}
	}
	log.Print(s)
}

func getUser1(ch chan<- int, n int, quit chan struct{}) {
	for i := 0; i < n; i++ {
		go func() {
			if rand.Intn(3) == 2 {
				log.Print("玩家退出....")
				quit <- struct{}{}
			}
			time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond)
			ch <- rand.Intn(10000)
		}()
	}
}

func partition2() {
	ch := make(chan int)
	quit := make(chan struct{})
	getUser1(ch, 10, quit)
	for {
		select {
		case user := <-ch:
			log.Print(user)
		case userQuit := <-quit:
			log.Print(userQuit)
		default:
			time.Sleep(time.Millisecond)

		}
	}
}

func getUser3(wg *sync.WaitGroup) chan int {
	ch := make(chan int)
	go func() {
		defer wg.Done()
		for user := range ch {
			log.Print(user)
		}
	}()
	return ch
}

func getUser4(done chan struct{}) chan int {
	ch := make(chan int)
	go func() {
		for user := range ch {
			log.Print(user)
			done <- struct{}{}
		}
	}()
	return ch
}

func partition4() {
	n := 10
	wg := &sync.WaitGroup{}
	var chans [10]chan int
	for i := 0; i < n; i++ {
		chans[i] = getUser3(wg)
	}

	for i := 0; i < n; i++ {
		chans[i] <- rand.Intn(100000)
		close(chans[i])
	}
	select {
	default:
		time.Sleep(time.Second)
	}
}

func partition5() {
	n := 10
	var chans [10]chan int
	wg := &sync.WaitGroup{}

	for i := 0; i < n; i++ {
		chans[i] = getUser3(wg)
	}
	wg.Add(n)
	for i := 0; i < n; i++ {
		chans[i] <- rand.Intn(100000)
		close(chans[i])
	}
	wg.Wait()
}
func partition6() {
	n := 10
	var chans [10]chan int
	done := make(chan struct{})
	for i := 0; i < n; i++ {
		chans[i] = getUser4(done)
	}
	for i := 0; i < n; i++ {
		a := rand.Intn(100000)
		log.Print(a)
		chans[i] <- a
		<-done
	}
}

func main() {

}
